package org.jgs1904.tieba.controller;

import lombok.extern.slf4j.Slf4j;
import org.jgs1904.tieba.entity.User;
import org.jgs1904.tieba.entity.UserMail;
import org.jgs1904.tieba.enums.UserMailStatusEnum;
import org.jgs1904.tieba.service.UserMailService;
import org.jgs1904.tieba.utils.UUIDUtil;
import org.jgs1904.tieba.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author junki
 * @date 2020/5/14 13:51
 */
@Controller
@RequestMapping("email")
@Slf4j
public class EmailController {

    /**
     * 注入javamail发送bean
     */
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 注入thymeleaf的模板引擎
     */
    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private UserMailService userMailService;

    @Value("${spring.mail.username}")
    private String mailForm;

    @GetMapping("active")
    @ResponseBody
    public Object active(@SessionAttribute("onlineUser") User user) {

        // 发送普通邮件
//        SimpleMailMessage message = new SimpleMailMessage();
//
//        message.setFrom(mailForm);
//        message.setTo(user.getEmail());
//        message.setSubject("JGS1904贴吧-激活邮箱");
//        message.setText("<a href='#'>点击激活邮箱！</a>");
//
//        javaMailSender.send(message);

        try {
            // 发送模板邮件
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(mailForm);
            messageHelper.setTo(user.getEmail());
            messageHelper.setSubject("JGS1904贴吧-激活邮箱");

            // 使用thymeleaf模板
            Context context = new Context();
            // 设置模板数据
            context.setVariable("nickname", user.getNickname());

            // 生成一个token对应用户id
            String token = UUIDUtil.getUUID(132);
            userMailService.save(UserMail.builder().token(token).userId(user.getId()).status(UserMailStatusEnum.UNUSED).build());

            context.setVariable("activeUrl", "http://localhost:8080/email/active/" + token);
            // 将数据绑定到模板
            String emailContent = templateEngine.process("/email/active", context);
            // 将结果设置到邮件对象
            messageHelper.setText(emailContent, true);

            // 发送邮件
            javaMailSender.send(message);
        } catch (MessagingException e) {
            log.error("激活邮件发送错误==>{}", e.getMessage());
            return ResultVo.builder().code(200).message("激活邮件发送失败，请稍后重试！").build();
        }

        return ResultVo.builder().code(200).message("激活邮件已发送，激活后请重新登录！").build();
    }

    @GetMapping("active/{token}")
    public String active(@PathVariable("token") String token, Model model) {

        UserMail userMail = userMailService.activeByToken(token);

        if (userMail.getStatus().equals(UserMailStatusEnum.USED)) {
            model.addAttribute("message", "激活成功！");
        } else {
            model.addAttribute("message", "激活失败！");
        }

        return "email/activeResult";
    }

}
